package com.lms.busi.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lms.admin.api.SysUserClient;
import com.lms.busi.common.mapper.TLmsStaffMapper;
import com.lms.busi.common.res.TLmsStaffRes;
import com.lms.busi.common.service.ITLmsStaffEducationService;
import com.lms.busi.common.service.ITLmsStaffService;
import com.lms.busi.common.service.ITLmsStaffWorkService;
import com.lms.common.entity.SysUser;
import com.lms.common.entity.TLmsStaff;
import com.lms.common.entity.TLmsStaffEducation;
import com.lms.common.pure.entity.ITreeNode;
import com.lms.common.pure.http.HttpResponse;
import com.lms.common.pure.utils.PinyinUtil;
import com.lms.common.pure.utils.StringUtil;
import com.lms.common.web.service.impl.WrapperServiceImpl;
import com.lms.common.web.utils.CheckEntityResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

@Service
@RequiredArgsConstructor
public class TLmsStaffServiceImpl extends WrapperServiceImpl<TLmsStaffMapper, TLmsStaff> implements ITLmsStaffService {

    private final ITLmsStaffEducationService lmsStaffEducationService;
    private final ITLmsStaffWorkService lmsStaffWorkService;

    private final SysUserClient sysUserClient;

    @Override
    public IPage<?> queryMapper(Page<TLmsStaff> page, Map<String, Object> p) {
        IPage<TLmsStaffRes> res = this.baseMapper.query(page, p);
        res.getRecords().forEach(item -> {
            // 查询毕业院校
            TLmsStaffEducation educationInfo = lmsStaffEducationService.getHighestEducationLevelByStaffId(item.getId());
            if (educationInfo != null) {
                // 毕业院校
                item.setEducationFrom(educationInfo.getName());
                // 专业名称
                item.setMajorStudied(educationInfo.getMajorStudied());
                // 学历
                item.setEducationLevelType(educationInfo.getEducationLevelType());
            }
        });
        return res;
    }

    public CheckEntityResult beforeInsert(TLmsStaff entity) {
        CheckEntityResult result = CheckEntityResult.getInstance();
        // 判断插入的姓名是否为中文
        String name = entity.getName();
        if (StringUtil.isEmpty(name)) {
            result.add("name", "姓名不能为空！");
            return result;
        }
        if (!PinyinUtil.isChineseText(name)) {
            result.add("name", "姓名必须为中文！");
            return result;
        }
        // 插入员工信息之前，首先创建账号信息
        // 先写死个试试看
        String username = PinyinUtil.getFullSpellSmallLetter(name);
        // 判断username是否存在于库中
        QueryWrapper<TLmsStaff> filter = new QueryWrapper<>();
        filter.likeRight("name", username);
        List<TLmsStaff> staffs = this.baseMapper.selectList(filter);
        int index = 0;
        for (TLmsStaff staff : staffs) {
            String staffNameRemain = staff.getName().replaceAll(username, "");
            // 剩余部分如果是纯数字，则名字相同
            if (StringUtil.isNumeric(staffNameRemain)) {
                index++;
            }
        }
        if (index > 0) {
            username += (index + 1);
        }
        Map<String, Object> userParams = new HashMap<>();
        userParams.put("username", username);
        userParams.put("nickname", entity.getName());
        // 初始化密码，密码为身份证后六位，如果没有填写身份证，则密码为用户名，这个就不用在这里管了
        String idCard = entity.getIdCard();
        if (StringUtil.isNotEmpty(idCard)) {
            userParams.put("password", idCard.substring(idCard.length() - 6));
        }
        HttpResponse<SysUser> res = sysUserClient.save(userParams);
        if (res.isSuccess()) {
            entity.setUserId(res.getData().getId());
        }
        return result;
    }

    @Override
    public void afterDelete(Serializable id) {
        // 删除员工信息后，需删除相应的教育经历等信息
        lmsStaffEducationService.deleteByStaffId(id);
        lmsStaffWorkService.deleteByStaffId(id);
    }

    @Override
    public List<ITreeNode<String>> getByOrganization(List<ITreeNode<String>> organizationaTreeList) {
        // 查询出所有在职的员工
        // STAFF_STATUS_003
        Map<String, Object> filter = new HashMap<>();
        filter.put("notStatus", "STAFF_STATUS_003");
        List<TLmsStaffRes> staffs = this.baseMapper.query(filter);
        // 将查询出的员工放入到树结构中
        for (ITreeNode<String> org : organizationaTreeList) {
            setTree(org, staffs);
        }
        return organizationaTreeList;
    }

    private void setTree(ITreeNode<String> org, List<TLmsStaffRes> staffs) {
        List<ITreeNode<String>> list = org.getChildren();
        if (list == null) return;

        String orgId = org.getId();
        List<TLmsStaffRes> users = new ArrayList<>();
        for (int i = 0; i < staffs.size(); i++) {
            TLmsStaffRes staffRes = staffs.get(i);
            if (orgId.equals(staffRes.getDeptId())) {
//                org.addChild(staffRes);
                users.add(staffRes);
                staffs.remove(i);
                i--;
            }
        }

        if (!users.isEmpty()) {
            // 根据职位排序
            users.sort(Comparator.comparingInt(TLmsStaffRes::getPostSort));
            List<ITreeNode<String>> newList = new ArrayList<>(users);
            newList.addAll(list);
            list.clear();
            list.addAll(newList);
        }

        for (ITreeNode<String> o : list) {
            setTree(o, staffs);
        }
    }

    
}
